<template>
  <el-dialog v-model="visible" title="查看课程列表" width="95%" append-to-body style="height: 800px">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="课程编号" prop="id">
            <el-input v-model="queryParams.id" placeholder="请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="名称" prop="courseName">
            <el-input v-model="queryParams.courseName" placeholder="请输入" :disabled="isDisable"  clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学段" prop="coursePeriod">
            <el-input v-model="queryParams.coursePeriod" placeholder="请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="年级" prop="courseGrade">
            <el-input v-model="queryParams.courseGrade" placeholder="请输入年级" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="学科" prop="subjectName">
            <el-input v-model="queryParams.subjectName" placeholder="请输入" :disabled="isDisable"  clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="授课学校" prop="courseDept">
            <!-- <el-input v-model="queryParams.courseDept" placeholder="请输入" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.courseDept" placeholder="请选择学校" clearable>
              <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="地区" prop="courseArea">
            <el-input v-model="queryParams.courseArea" placeholder="请输入" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="授课时间" prop="courseDate">
            <el-date-picker clearable v-model="queryParams.courseDate" type="date" value-format="YYYY-MM-DD" placeholder="年/月/日" :disabled="isDisable" />
            <span style="margin: 0 5px"> - </span>
            <el-date-picker clearable v-model="queryParams.courseDate" type="date" value-format="YYYY-MM-DD" placeholder="年/月/日" :disabled="isDisable" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleAdd" v-hasPermi="['core:testTimeTable:add']">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <h2>实验课程表（列表）</h2>
      </template>

      <el-table v-loading="loading" :data="testTimeTableList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="课程编号" align="center" prop="id" v-if="true" />
        <el-table-column label="名称" align="center" prop="courseName" >
          <template #default="scope">
            <span>{{scope.row.courseName  || courseName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="学段" align="center" prop="coursePeriod" >
          <template #default="scope">
            <dict-tag :options="sys_period" :value="scope.row.coursePeriod"/>
          </template>
        
        </el-table-column>
        <el-table-column label="年级" align="center" prop="courseGrade" >
          <template #default="scope">
            <dict-tag :options="sys_grade" :value="scope.row.courseGrade" />
          </template>
        </el-table-column>
        <el-table-column label="学科" align="center" prop="courseSubject" >
          <template #default="scope">
                 {{ getSubjectNameById(subjectOptions, scope.row.courseSubject) }}
            </template>
        </el-table-column>
        <el-table-column label="授课地区" align="center" prop="courseAreaName" />
        <el-table-column label="授课学校" align="center" prop="courseDept" >
           <template #default="scope">
            {{getTenantById(tenantOptions,scope.row.courseDept)}}
          
          </template>
        </el-table-column>
        <el-table-column label="授课时间" align="center" prop="courseDate" width="180">
          <template #default="scope">
            <!-- <span>{{ parseTime(scope.row.courseDate, '{y}-{m}-{d}') }}</span> -->
            <span>{{ parseTime(scope.row.courseDate) }}</span>
            <span> - </span>
            <span>{{ parseTime(scope.row.courseDateEnd) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleUpdate(scope.row)" v-hasPermi="['core:testTimeTable:edit']">编辑</el-button>
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" v-hasPermi="['core:testTimeTable:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </el-dialog>
</template>

<script setup name="TestTimeTable" lang="ts">
import { listTestTimeTable, getTestTimeTable, delTestTimeTable, addTestTimeTable, updateTestTimeTable } from '@/api/core/testTimeTable';
import { TestTimeTableVO, TestTimeTableQuery, TestTimeTableForm } from '@/api/core/testTimeTable/types';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_notice_type, sys_period,sys_grade } = toRefs<any>(proxy?.useDict('sys_notice_type', 'sys_period','sys_grade'));

const testTimeTableList = ref<TestTimeTableVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const visible = ref(false);
const queryFormRef = ref<ElFormInstance>();
const testTimeTableFormRef = ref<ElFormInstance>();
  const isDisable =ref(false);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 共有数据方法  学科 ,教师
/** 公共方法 */
import { getSubjectNameById,getTeacherNameById ,getTenantById} from '@/utils/index';
import { useSubjectList ,useTeacherList} from '@/composables/useSubjectList';
const { subjectOptions, fetchSubjectList } = useSubjectList();
const { teacherOptions, fetchTeacherList } = useTeacherList();
import { useSchoolList,useTenantlList } from '@/composables/useSchoolList';
const { deptOptions, fetchSchoolList } = useSchoolList();
//学校改租户数据
const { tenantOptions, fetchTenantlList} = useTenantlList();
const initFormData: TestTimeTableForm = {
  courseId: undefined,
  coursePeriod: undefined,
  courseGrade: undefined,
  courseSubject: undefined,
  courseArea: undefined,
  courseDept: undefined,
  courseDate: undefined,
  courseDateEnd: undefined,
  courseName: undefined,
};
const data = reactive<PageData<TestTimeTableForm, TestTimeTableQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    courseId: undefined,
    coursePeriod: undefined,
    courseGrade: undefined,
    courseSubject: undefined,
    courseArea: undefined,
    courseDept: undefined,
    courseDate: undefined,
    courseDateEnd: undefined,
    courseName: undefined,
    subjectName: undefined,
    params: {}
  },
  rules: {
    courseId: [{ required: true, message: '课程不能为空', trigger: 'blur' }],
    coursePeriod: [{ required: true, message: '学段不能为空', trigger: 'blur' }],
    courseGrade: [{ required: true, message: '年级(班级)不能为空', trigger: 'blur' }],
    courseSubject: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
    courseArea: [{ required: true, message: '授课地区不能为空', trigger: 'blur' }],
    courseDept: [{ required: true, message: '授课学校不能为空', trigger: 'blur' }],
    courseDate: [{ required: true, message: '授课开始时间不能为空', trigger: 'blur' }],
    courseDateEnd: [{ required: true, message: '授课结束时间不能为空', trigger: 'blur' }]
  }
});
 const  courseName= ref()
const { queryParams, form, rules } = toRefs(data);
/** 弹窗 */
const openDialog = (row) => {
  if (row) {
    isDisable.value=true
    queryParams.value.courseName = row.courseName;
    console.log('======',row)
    courseName.value =row.courseName
    queryParams.value.subjectName = row.subjectName;
    queryParams.value.courseDate = row.courseDate;
    queryParams.value.courseDateEnd = row.courseDateEnd;
  }
  
  getList();
  visible.value = true;
};

/** 查询实验课程列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTestTimeTable(queryParams.value);
  testTimeTableList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  testTimeTableFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.courseName = courseName.value;
  handleQuery();

};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TestTimeTableVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  //   reset();
  //   dialog.visible = true;
  //   dialog.title = '添加实验课程';
  router.push({ path: '/couto/testTimeTable/panel/', query: { type: 0 } });
};

/** 修改按钮操作 */
const handleView = async (row?: TestTimeTableVO) => {
const _id = row?.id || ids.value[0];
router.push({ path: '/couto/testTimeTable/panel/', query: { id: _id, type: 2 } });
};
/** 修改按钮操作 */
const handleUpdate = async (row?: TestTimeTableVO) => {

  const _id = row?.id || ids.value[0];
  
  router.push({ path: '/couto/testTimeTable/panel/', query: { id: _id, type: 1 } });
};

/** 提交按钮 */
const submitForm = () => {
  testTimeTableFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTestTimeTable(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTestTimeTable(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TestTimeTableVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除实验课程编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delTestTimeTable(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'core/testTimeTable/export',
    {
      ...queryParams.value
    },
    `testTimeTable_${new Date().getTime()}.xlsx`
  );
};

defineExpose({
  openDialog
});
</script>
